All files / src/app/api/collections/[id]/purge route.ts

94.73% Statements 18/19
100% Branches 8/8
100% Functions 1/1
94.73% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                3x                     8x 8x 8x 8x   8x 8x 1x   7x 3x       4x 4x       4x 4x 1x           3x 2x   1x      
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireAuth } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { CollectionController } from "@/server/api/collections";
import { CollectionPurgeService } from "@/server/services/CollectionPurgeService";
import { errorResponse } from "@/server/api/http-errors";
 
const ConfirmSchema = z.object({ confirm: z.string() });
 
// Permanent owner-only cascade purge. Order matters for security: authenticate,
// resolve the collection INCLUDING soft-deleted (the canonical path is
// DELETE -> purge), gate as the OWNER, and ONLY THEN parse the confirm body —
// which must echo the exact collection name. A non-owner with any body gets
// 403/404, never a 400 that leaks the collection's existence or name.
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id } = await params;
    const user = await requireAuth();
    const db = getDb();
 
    const collection = await CollectionController.fromDb(db).getIncludingDeleted(id);
    if (!collection) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
    if (collection.ownerId !== user.id) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }
 
    let body: unknown;
    try {
      body = await request.json();
    } catch {
      return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
    }
    const parsed = ConfirmSchema.safeParse(body);
    if (!parsed.success || parsed.data.confirm !== collection.name) {
      return NextResponse.json(
        { error: "Type the collection name to confirm" },
        { status: 400 },
      );
    }
 
    await new CollectionPurgeService(db).purge(collection, user.id);
    return NextResponse.json({ message: "Collection purged" });
  } catch (error) {
    return errorResponse(error);
  }
}